from PyQt6.QtWidgets import QApplication, QWidget, QFrame, QPushButton, QLabel, QCheckBox, QStackedWidget, QProgressBar,QMessageBox
from PyQt6.QtGui import QIcon, QFont, QFontDatabase
from PyQt6.QtCore import Qt, QTimer, QEventLoop
import sys, os, shutil, webbrowser
 
class UI(QWidget):
    def __init__(self):
        super().__init__()

        self.winTitle = '万小盒 1.0.2'
        # 引入第三方字体
        QFontDatabase.addApplicationFont("./support/SourceHanMonoSC-Bold.otf")
        # 启动
        self.setWindowIcon(QIcon('./support/logo64x.ico'))
        self.setWindowTitle(self.winTitle)
        # 大小位置 背景
        self.w = 500
        self.h = 360
        self.x = int((self.screen().availableGeometry().width() - self.w) / 2)
        self.y = int((self.screen().availableGeometry().height() - self.h) / 2)
        self.setGeometry(self.x, self.y, self.w, self.h)
        self.setStyleSheet("background-color:#dd960f;")

        # 标题栏设置
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
        self.closeBtn = QPushButton('×', self)
        self.closeBtn.setFont(QFont("Source Han Mono SC", 16))
        self.closeBtn.setGeometry(self.w-24, 0, 24, 19)
        self.closeBtn.setStyleSheet("QPushButton{border:none;text-align:center;padding-bottom:3px;color:#ffffff;}"
                                "QPushButton:hover{background-color:#ff0000;}")
        self.closeBtn.clicked.connect(self.onCloseBtnClick)
        self.title = QLabel(self)
        self.title.setText(self.winTitle)
        self.title.setFont(QFont("Source Han Mono SC", 10))
        self.title.move(3, 0)
        self.title.setStyleSheet("QLabel{color:#ffffff;}")

        # 上半部分中间添加一个图片
        self.logo = QLabel(self)
        self.logo.setGeometry(189, 52, 121, 157)
        self.logo.setStyleSheet("background-image:url('./support/logo.png')")

        # 创建下部分
        self.sW = QStackedWidget(self)
        self.sW.setGeometry(0, 240, self.w, self.h - 240)
        # 第一页
        self.frame = QFrame()
        self.frame.setGeometry(0, 240, self.w, self.h - 240)
        self.frame.setStyleSheet("QFrame{background-color:#eeeeee;}")

        self.anBtn = QPushButton("立即安装", self.frame)
        self.anBtn.setFont(QFont("Source Han Mono SC", 16))
        self.anBtn.setGeometry(190, 20, 120, 40)
        self.anBtn.setStyleSheet("QPushButton{border:none;text-align:center;padding-bottom:3px;color:#ffffff;border-radius:3px;background-color:#dd960f;}"
                                "QPushButton:hover{background-color:#e4ab31;}")
        self.anBtn.clicked.connect(self.onAnBtnClick)

        self.isQuan = QCheckBox(self.frame)
        self.isQuan.setText("全局安装")
        self.isQuan.setFont(QFont("Source Han Mono SC", 10))
        self.isQuan.setStyleSheet("QCheckBox{background-color:#eeeeee;color:#252525;}"
                                  "QCheckBox::indicator{width:12px;height:12px;border:1px solid #252525;border-radius:2px;margin:0px -3px -2px 0px;}"
                                  "QCheckBox::indicator:checked{border:1px solid #dd960f;background-image:url('./support/duihao.png');}")
        self.isQuan.move(10, 93)
        self.isQuan.setCheckState(Qt.CheckState.Checked)
        self.sW.addWidget(self.frame)

        # 第二页
        self.frame1 = QFrame()
        self.frame1.setGeometry(0, 240, self.w, self.h - 240)
        self.frame1.setStyleSheet("QFrame{background-color:#eeeeee;}")
        # 创建一个进度条
        self.closePBar = True
        self.pBar = QProgressBar(self.frame1)
        self.pBar.setRange(0, 100)
        self.pBar.setGeometry(100, 40, 300, 20)
        self.pBar.setStyleSheet("QProgressBar{border-radius:3px;background-color:#ffffff;text-align:center;color:#cccccc;}"
                                "QProgressBar::chunk{background-color:#dd960f;}")
        self.pBarTitle = QLabel(self.frame1)
        self.pBarTitle.setText('准备安装...，安装进度：%d%%' % 0)
        self.pBarTitle.setFont(QFont("Source Han Mono SC", 10))
        self.pBarTitle.setGeometry(100, 62, 300, 12)
        self.pBarTitle.setStyleSheet("QLabel{color:#dd960f;}")
        self.sW.addWidget(self.frame1)
         # 第三页
        self.frame2 = QFrame()
        self.frame2.setGeometry(0, 240, self.w, self.h - 240)
        self.frame2.setStyleSheet("QFrame{background-color:#eeeeee;}")
        self.wcBtn = QPushButton("安装完成", self.frame2)
        self.wcBtn.setFont(QFont("Source Han Mono SC", 16))
        self.wcBtn.setGeometry(190, 20, 120, 40)
        self.wcBtn.setStyleSheet("QPushButton{border:none;text-align:center;padding-bottom:3px;color:#ffffff;border-radius:3px;background-color:#dd960f;}"
                                "QPushButton:hover{background-color:#e4ab31;}")
        self.wcBtn.clicked.connect(self.onWcBtnClick)
        self.isOpenHome = QCheckBox(self.frame2)
        self.isOpenHome.setText("打开主页")
        self.isOpenHome.setFont(QFont("Source Han Mono SC", 10))
        self.isOpenHome.setStyleSheet("QCheckBox{background-color:#eeeeee;color:#252525;}"
                                    "QCheckBox::indicator{width:12px;height:12px;border:1px solid #252525;border-radius:2px;margin:0px -3px -2px 0px;}"
                                    "QCheckBox::indicator:checked{border:1px solid #dd960f;background-image:url('./support/duihao.png');}")
        self.isOpenHome.move(10, 93)
        self.isOpenHome.setCheckState(Qt.CheckState.Checked)

        self.sW.addWidget(self.frame2)
        # 选中
        self.sW.setCurrentIndex(0)
        
    def onCloseBtnClick(self):
        mbox = QMessageBox(self)
        mbox.setText("你确定要退出万小盒<br>安装程序吗?")
        mbox.setWindowTitle("消息提示")
        mbox.setIcon(QMessageBox.Icon.Question)
        mbox.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel)
        mbox.setDefaultButton(QMessageBox.StandardButton.Cancel)
        mboxBtnY = mbox.button(QMessageBox.StandardButton.Yes)
        mboxBtnY.setText("确定")
        mboxBtnC = mbox.button(QMessageBox.StandardButton.Cancel)
        mboxBtnC.setText("取消")
        mboxBtnY.clicked.connect(self.closeAll)
        mbox.setStyleSheet("QMessageBox{background-color:#eeeeee;}"
                        "QMessageBox QPushButton{border:none;text-align:center;padding:3px 10px;color:#ffffff;border-radius:3px;background-color:#cccccc;}"
                        "QMessageBox QPushButton:hover{background-color:#dd960f;}"
                        "QMessageBox QPushButton:focus{background-color:#dd960f;}"
                        "QMessageBox QLabel{background-color:#eeeeee;}")
        mbox.show()

    # 执行关闭
    def closeAll(self):
        self.closePBar = False
        self.close()
        self.loop.quit()
        QApplication.quit()

    def pBarRun(self, mval, mtext):
        oval = self.pBar.value() if self.pBar.value() > 0 else 0
        for i in range(oval, mval):
            self.pBar.setValue(i)
            self.pBarTitle.setText('%s，安装进度：%d%%' % (mtext, i))
            self.mSleep(50)
        return 'Y' if self.closePBar else 'N'

    def mSleep(self, msec):
        self.loop = QEventLoop(self)
        self.timer = QTimer(self)
        self.timer.singleShot(msec, self.loop.quit)
        self.loop.exec()
    
    def onAnBtnClick(self):
        self.sW.setCurrentIndex(1)
        path = ''
        reok = False
        if self.pBarRun(10, '开始安装') == 'Y' and self.pBarRun(20, '检查系统环境') == 'Y':
            if sys.platform == 'win32':
                if self.pBarRun(30, '检查系统环境：window') == 'Y' and self.pBarRun(40, '是否全局安装') == 'Y':
                    if self.isQuan.isChecked() and self.pBarRun(50, '是否全局安装：是') == 'Y':
                        path = "C:\\Program Files\\Common Files\\Adobe\\CEP\\extensions\\"
                        reok = True
                    elif self.pBarRun(50, '是否全局安装：否') == 'Y':
                        path = "C:\\Users\\" + os.getlogin() + "\\AppData\\Roaming\\Adobe\\CEP\\extensions\\"
                        reok = True
            elif sys.platform == 'darwin':
                if self.pBarRun(30, '检查系统环境：macOS') == 'Y' and self.pBarRun(40, '是否全局安装') == 'Y':
                    if self.isQuan.isChecked() and self.pBarRun(50, '是否全局安装：是') == 'Y':
                        path = "/Library/Application Support/Adobe/CEP/extensions/"
                        reok = True
                    elif self.pBarRun(50, '是否全局安装：否') == 'Y':
                        path = "/Users/" + os.getlogin() + "/Library/Application Support/Adobe/CEP/extensions/"
                        reok = True
                    
        wzd = 0
        if reok == True and path != '':
            # 安装
            realPath = path + 'com.ateng.wanxiaohe'
            # 删除老版本
            if self.pBarRun(60, '检查是否有老版本，有就删除') == 'Y':
                if os.path.exists(realPath):
                    shutil.rmtree(realPath)
                # 复制进入新版本
                if self.pBarRun(70, '复制文件') == 'Y':
                    shutil.copytree('./support/com.ateng.wanxiaohe', realPath)
                    # 检查文件完整度1
                    if self.pBarRun(80, '检查文件完整度1') == 'Y':
                        if os.path.exists(realPath + '/CSXS/manifest.xml'):
                            wzd = wzd + 1
                        # 检查文件完整度2
                        if self.pBarRun(85, '检查文件完整度2') == 'Y':
                            if os.path.exists(realPath + '/jsx/main.jsx'):
                                wzd = wzd + 1
                            # 检查文件完整度3
                            if self.pBarRun(90, '检查文件完整度3') == 'Y':
                                if os.path.exists(realPath + '/html/index.html'):
                                    wzd = wzd + 1
            

        if wzd == 3 and reok == True:
            if self.pBarRun(100, '安装完成') == 'Y':
                self.sW.setCurrentIndex(2)
            else:
                reok = False
        else:
            self.pBarRun(95, '安装失败')
            reok = False

        # 结束
        if reok == False:
            self.closeAll()

    def onWcBtnClick(self):
        if self.isOpenHome.isChecked():
            webbrowser.open('https://gitee.com/atengs/wanxiaohe')
        # 退出
        self.closeAll()
 
if __name__ == "__main__":
    app = QApplication(sys.argv)
    ui = UI()
    ui.show()
    sys.exit(app.exec())
 